package www.dianbaozu.com.ui.server.topping

import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.viewModelScope
import com.netease.nim.uikit.api.NIMRepository
import com.netease.nimlib.sdk.msg.model.IMMessage
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.*
import www.wen.com.common.lib.data.repository.AppDataManager

class ToppingViewModel @ViewModelInject constructor(private val appDataManager: AppDataManager) :
    BaseViewModel() {

    @FlowPreview
    fun getServerChannelTopMsgList(
        teamId: String,
        action: ((Result.Success<List<IMMessage>>) -> Unit)
    ) {
        viewModelScope.launch {
            appDataManager.getServerChannelTopMsgListFlow(teamId)
                .catch { cause ->
                    loading.value = UiStateCustom(
                        stateData = LoadingDialog(
                            tip = cause.message ?: "网络异常",
                            loadingDialogStateType = LoadingDialogStateType.ERROR,
                            isShowDialogTip = false,
                            isShowToastTip = true
                        )
                    )
                }
                .collect {
                    if (it.data.isNotEmpty()) {
                        it.data.forEach { topMsgEntityItem ->
                            pullMessageHistory(teamId,topMsgEntityItem, action)
                        }
                    }
                }
        }
    }

    private fun pullMessageHistory(
        teamId: String,
        topMsgEntityItem: TopMsgEntityItem,
        action: ((Result.Success<List<IMMessage>>) -> Unit)
    ) {
        viewModelScope.launch {
            flow {
                try {
                    emit(
                        Result.Success(
                            NIMRepository.pullMessageHistoryExType(
                                teamId,
                                topMsgEntityItem.msgTime,
                                topMsgEntityItem.uuId
                            )
                        )
                    )
                } catch (e: Exception) {
                    throw e
                }
            }.retryWhen { cause, attempt ->
                return@retryWhen cause.message == "网络异常" && attempt <= 1
            }
                .catch { cause ->
                    loading.value = UiStateCustom(
                        stateData = LoadingDialog(
                            tip = cause.message ?: "网络异常",
                            loadingDialogStateType = LoadingDialogStateType.ERROR,
                            isShowDialogTip = false,
                            isShowToastTip = true
                        )
                    )
                }
                .collect {
                    action.invoke(it)
                }
        }
    }

}